package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.Category;
import com.wpf.system.mapper.CategoryMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/category")
public class CategoryController {

    @Resource
    private CategoryMapper categoryMapper;

    @GetMapping
    public List<Category> getCategory(){
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime));
    }

    @GetMapping("/id")
    public Category getCategoryById(@RequestParam("id") Long id){
        return categoryMapper.selectById(id);
    }

    @PreAuthorize("hasAuthority('sys:dictionary:category')")
    @PostMapping
    public ResultVO addCategory(@RequestBody Category category){
        if(Convert.toBool(categoryMapper.insert(category))){
            return ResultUtils.success("添加新运动类别成功！");
        }else{
            return ResultUtils.error("添加新运动类别失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dictionary:category')")
    @PutMapping
    public ResultVO editCategory(@RequestBody Category category){
        if(Convert.toBool(categoryMapper.updateById(category))){
            return ResultUtils.success("修改运动类别名称成功！");
        }else{
            return ResultUtils.error("修改运动类别名称失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dictionary:category')")
    @PutMapping("/sort")
    public ResultVO sortCategory(@RequestBody List<Category> categorylist){
        int count = 0;
        for(Category category : categorylist){
            count += categoryMapper.updateById(category);
        }
        if(count==categorylist.size()){
            return ResultUtils.success("排序成功！");
        }else{
            return ResultUtils.error("排序失败！请重试！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dictionary:category')")
    @DeleteMapping("/{id}")
    public ResultVO deleteCategory(@PathVariable("id") Long id){
        if(Convert.toBool(categoryMapper.deleteById(id))){
            return ResultUtils.success("删除运动类别成功！");
        }else{
            return ResultUtils.error("删除运动类别失败！");
        }
    }


}
